/* eslint-disable array-callback-return */
/* eslint-disable no-case-declarations */
// Import Swiper React components
import DragModal from '@/components/DragModal';
import { EditPro } from '@/components/DragModal/formdoms';
import { doFetch } from '@/utils/doFetch';
import {
  ArrowUpOutlined,
  DeleteFilled,
  EditFilled,
  EyeFilled,
  SearchOutlined,
  VerticalAlignMiddleOutlined,
  VerticalAlignTopOutlined,
} from '@ant-design/icons';
import { useModel } from '@umijs/max';
import {
  Avatar,
  Dropdown,
  Empty,
  Input,
  Progress,
  Tooltip,
  theme,
} from 'antd';
import { useEffect, useMemo, useState } from 'react';
// Import Swiper styles
import useCurrentUser from '@/utils/useCurrentUser';
import { useRequest } from 'ahooks';
import { List, AutoSizer } from 'react-virtualized';
import './index.less';
import { Switch } from 'antd';
import filterByPinyin from '@/utils/filterByPinyin';
import ProjectDetail from './projectDetail';
import SvgDot from '../SvgDot'
import useMyProjectList from '@/utils/useMyProjectList';
import { useWindowSize } from '@/utils/windowsize';
import { statusConf } from '@/utils/global';


const ProItem = ({ it, changeCurPro, refresh, curpro, currentUser }) => {
  const { token } = theme.useToken();
  const {
    colorText,
    colorPrimary,
    colorOppsites,
    colorBgCard,
    colorBgSeven,
    subMenuItemBg
  } = token;

  const [modal, setModal] = useState({
    open: false,
  });

  //是否是我的
  const isMine = currentUser?.id === it?.projectUserId;

  const curmenus = useMemo(() => {
    const items = [
      {
        label: '置顶',
        key: '11',
        icon: <VerticalAlignTopOutlined />,
      },
      {
        label: '取消置顶',
        key: '10',
        icon: <VerticalAlignMiddleOutlined />,
      },
    ];

    const menu1 = items.filter((itz) => {
      const istopNum = it?.isTop === 1 ? '10' : '11';
      return [istopNum].includes(itz.key) || itz?.type;
    });

    const menu2 = isMine ? [{
      type: 'divider',
    },
    {
      label: '编辑',
      key: 'edit',
      icon: <EditFilled />,
    },
    {
      label: '删除',
      key: 'delete',
      danger: true,
      icon: <DeleteFilled />,
    }] :
      [];

    return [...menu1, ...menu2];
  }, [isMine, it]);

  //删除操作
  const { run } = useRequest(doFetch, {
    manual: true,
    onSuccess: (result) => {
      if (result.code === 0) {
        refresh();
      }
    },
  });

  // 修改用户状态
  const { updateUser } = useCurrentUser();


  const handleClick = async ({ key, domEvent }, item) => {
    //阻止冒泡
    domEvent.stopPropagation();
    switch (key) {
      case '10':
        await doFetch({
          url: '/userProject',
          params: {
            projectId: item?.id,
            isTop: 0,
          },
          method: 'PUT',
        });
        refresh();

        break;
      case '11':
        await doFetch({
          url: '/userProject',
          params: {
            projectId: item?.id,
            isTop: 1,
          },
          method: 'PUT',
        });
        refresh();

        break;
      case 'edit':
        setModal({
          open: true,
          title: '编辑项目',
          item: it,
        });
        break;
      case 'delete':
        run({ url: '/project/' + it?.id, params: {}, method: 'DELETE' });
        break;
      default:
        break;
    }
  };
  //当前选中项目
  const ifs = curpro?.id === it?.id;
  const headbg = ifs ? { backgroundColor: colorPrimary } : { backgroundColor: colorBgSeven };
  //是否提示
  const istip = currentUser?.guide?.pcr === true ? { open: false } : {};
  //进度条的颜色
  const strokeColor = useMemo(() => {
    return currentUser.theme === 'light' ? (ifs ? {
      "0%": '#fec163',
      '70%': '#ff4800',
    } : {
      "0%": '#999',
      '100%': '#000',
    }) : (ifs ? {
      "0%": '#17ead9',
      '70%': '#6078ea',
    } : {
      "0%": '#999',
      '70%': '#fff',
    })
  }, [currentUser.theme, ifs]);
  return (
    <>
      <DragModal
        {...modal}
        onCancel={() => {
          setModal(() => ({
            open: false,
          }));
        }}
        zIndex={1000}
        width={650}
        style={{
          '--backgroundColor': colorBgSeven,
          top: 12,
        }}
      >
        <EditPro
          projectId={it?.id}
          refresh={() => {
            refresh();
            setModal((s) => ({ ...s, open: false }));
          }}
          defaultValue={modal?.item}
        ></EditPro>
      </DragModal>
      <Dropdown
        menu={{
          items: curmenus,
          onClick: (info) => handleClick(info, it)
        }}
        trigger={['contextMenu']}
        zIndex={1000}
      >
        <Tooltip
          {...istip}
          arrow={false}
          placement='bottomLeft'
          zIndex={1}
          title={<span className='centerl' style={{ gap: 6 }}>
            <span>右键点击可唤醒菜单</span>
            <a onClick={async () => {
              //key pcr
              updateUser.runAsync({
                guide: {
                  ...(currentUser.guide ?? {}),
                  pcr: true,
                }
              })
            }}>知道了</a></span>}
        >
          <div
            onClick={() => {
              changeCurPro(ifs ? {} : {
                ...it
              });
            }}
            style={{
              width: '100%',
              userSelect: "none",
              color: ifs ? colorPrimary : colorText,
              transition: 'all 0.4s',
              borderRadius: 10,
              backgroundColor: it?.isTop === 1 ? colorOppsites : colorBgCard,
              cursor: "pointer",
              padding: "12px 12px 8px 12px",
              overflow: "hidden",
              backdropFilter: "blur(8px)"
            }}>
            <div className="columns">
              <div style={{ gap: 12, display: 'flex' }}>
                <Avatar src={it?.logoUrl} size={42} shape="square" style={{
                  ...headbg,
                  color: ifs ? subMenuItemBg : colorText,
                  fontWeight: "bolder",
                  flexShrink: 0,
                  borderRadius: 7
                }}
                  className={ifs ? 'animatedbg' : ''}

                >
                  {it.projectName?.charAt(0)}
                </Avatar>


                <div className="columns" style={{ flex: 1, overflow: 'hidden' }}>
                  <div className="spread">
                    <b className='oneline' style={{ flex: 1, overflow: 'hidden' }}>{it.projectName}</b>
                    <SvgDot color={statusConf[it.status].color} title={statusConf[it.status].text}></SvgDot>
                  </div>

                  <div style={{ width: "100%", gap: 10, marginTop: 5 }} className='spread'>
                    <Progress
                      style={{ margin: 0, opacity: 0.7, width: 100 }}
                      percent={it.allItemCount !== 0 ? parseInt(it.finishItemCount * 100 / it.allItemCount) : 0}
                      showInfo={false}
                      size="small"
                      strokeColor={strokeColor}
                    />

                    <b style={{ fontSize: 12, opacity: 0.8 }}>
                      {it.finishItemCount}/{it.allItemCount}
                    </b>
                  </div>

                </div>
              </div>
            </div>
          </div>
        </Tooltip>

      </Dropdown>
    </>
  );
};

export default function Myprojects({ setExtra, refresh }) {
  const { token } = theme.useToken();
  const { colorBgSecondary } = token;
  const [filter, setFilter] = useState({
    keywords: null,
    sortByTime: 0,
  });

  const { keywords, sortByTime } = filter;

  const { initialState, setInitialState, myProList, getMyPro } = useMyProjectList(keywords);

  const { curpro, currentUser, updateProject } = initialState;

  const [status, setStatus] = useState([0, 1, 3]);

  //刷新数据
  useEffect(() => {
    getMyPro.run({
      statusList: status,
      sortByTime
    })
  }, [status, sortByTime, refresh, updateProject]);



  // 顶部dom
  useEffect(() => {
    setExtra(
      <div
        style={{ userSelect: 'none' }}
        onClick={(e) => {
          e.stopPropagation();
        }}
      >
        <Switch
          style={{ marginRight: -4 }}
          checked={status.length === 1 && status[0] === 2}
          checkedChildren='已完成'
          unCheckedChildren='进行中'
          onChange={(val) => {
            if (!val) {
              setStatus([0, 1, 3])
            } else {
              setStatus([2])
            }
          }}></Switch>
      </div>,
    );
  }, [status]);



  //修改选中的项目id
  const changeCurPro = (val) => {
    setInitialState((s) => ({
      ...s,
      curpro: val,
    }));
  };

  const proList = myProList.filter(pro => keywords ? filterByPinyin(pro.projectName, keywords) : true);
  const { height } = useWindowSize();

  return <div>
    <div className="spread" style={{ gap: 6, marginBottom: 8 }}>
      <Tooltip title={sortByTime === 1 ? '最早创建' : '最近创建'} placement='bottomLeft'>
        <div className='sorts' style={{ backgroundColor: colorBgSecondary }} onClick={() => {
          setFilter(s => ({
            ...s,
            sortByTime: sortByTime === 1 ? 0 : 1
          }))
        }}>
          <ArrowUpOutlined rotate={sortByTime === 1 ? 180 : 0} />
        </div>
      </Tooltip>
      <Input
        prefix={<SearchOutlined />}
        value={keywords}
        onChange={e => {
          setFilter(s => ({
            ...s,
            keywords: e.target.value
          }))
        }}
        style={{ borderRadius: 6, backgroundColor: colorBgSecondary, flex: 1 }}
        variant="borderless"
        placeholder='查询 / 支持拼音'></Input>
    </div>
    {
      proList?.length > 0 ? (
        <AutoSizer disableHeight>
          {() => (
            <List
              className="element hidescroll"
              width={250}
              height={proList.length * 78 > (height - 200) ? (height - 200) : proList.length * 86}
              rowCount={proList.length}
              rowHeight={84}
              rowRenderer={({
                key, // Unique key within array of rows
                index, // Index of row within collection
                style, // Style object to be applied to row (to position it)
              }) => {
                const it = proList[index];
                if (it) {
                  //下方的 div 必须 否则拼命闪
                  return <div key={key} style={{ ...style, justifyContent: "flex-start" }} className='center'>
                    <ProItem
                      it={it}
                      changeCurPro={changeCurPro}
                      refresh={getMyPro.refreshAsync}
                      curpro={curpro}
                      currentUser={currentUser}
                      setInitialState={setInitialState}
                    />
                  </div>

                } else {
                  return null;
                }

              }}
            />)}
        </AutoSizer>
      ) : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} style={{ marginTop: 58 }} />
    }

  </div>;
}
